
wbx.model = (() => {
  let cellsData = [];

  const row = {
    count: 0,
    heights: []
  };
  const column = {
    count: 0,
    widths: []
  };

  let configMap = {
    columnWidth: 0
  }

  /**
   * 将json数据转换为二维数组数据
   * @param
   * @return {string[][]} 二维数组数据
   */
  const transformData = (originalData, rowLength, columnLength) => {
    // 有数据 行列以数据为准
    if (originalData) {
      const fields = originalData.fields;

      // 第一列是空
      fields.unshift('');

      let items = originalData.items;
      // 第一列是编号
      items = items.map((item, index) => {
        item.unshift(index + 1);
        return item;
      })

      if (fields.length > 0) {
        columnLength = fields.length;
        rowLength = items.length + 1;
        const rawData = items;
        rawData.unshift(fields);
        return rawData;
      } else {
        return null;
      }
    } else {
      // 没有数据 生成空的行列
      let rawData = [];
      for (let i = 0; i < rowLength; i++) {
        if (typeof rawData[i] === 'undefined') {
          rawData[i] = [];
        }
        for (let j = 0; j < columnLength; j++) {
          // rawData[i].push('');
          // rawData[i].push(`${i}:${j}`);
          rawData[i].push('');
        }
      }
      return rawData;
    }
  };

  const init = (options) => {
    console.log('model init');
    const {
      rowLength,
      columnLength,
      rowHeight,
      columnWidth,
      data
    } = options;

    row.count = rowLength;
    row.heights = Array(rowLength).fill(rowHeight);

    column.count = options.columnLength;
    column.widths = Array(columnLength).fill(columnWidth);

    cellsData = transformData(data, rowLength, columnLength);
  };

  const getCellsData = () => cellsData;

  // 保存数据
  const save = (text, rowIndex, columnIndex) => {
    cellsData[rowIndex][columnIndex] = text;
  };

  return {
    init: init,
    row: row,
    column: column,
    getCellsData: getCellsData,
    save: save
  };

})();